package notification

import (
	"context"
	"log"
	"time"

	"alfred/database"
	"alfred/models"

	"gitee.com/damengde/teemo"
)

type Notifier struct {
	db *database.DB
}

// NewNotifier 创建新的通知器
func NewNotifier(db *database.DB) *Notifier {
	return &Notifier{db: db}
}

// NotificationMessage 通知消息结构
type NotificationMessage struct {
	Type        string     `json:"type"`
	FlowName    string     `json:"flow_name"`
	FlowID      string     `json:"flow_id"`
	ExecutionID string     `json:"execution_id"`
	Branch      string     `json:"branch"`
	CommitID    string     `json:"commit_id"`
	Status      string     `json:"status"`
	Error       string     `json:"error,omitempty"`
	StartTime   time.Time  `json:"start_time"`
	EndTime     *time.Time `json:"end_time,omitempty"`
	Timestamp   time.Time  `json:"timestamp"`
}

// SendFailureNotification 发送失败通知
func (n *Notifier) SendFailureNotification(flow *models.Flow, execution *models.FlowExecution, err error) {
	// 获取通知配置
	configs, dbErr := n.db.GetNotificationConfigs()
	if dbErr != nil {
		log.Printf("Failed to get notification configs: %v", dbErr)
		return
	}

	if len(configs) == 0 {
		log.Println("No notification configs found")
		return
	}

	// 构建通知消息
	message := NotificationMessage{
		Type:        "flow_failure",
		FlowName:    flow.Name,
		FlowID:      flow.ID,
		ExecutionID: execution.ID,
		Branch:      execution.Branch,
		CommitID:    execution.CommitID,
		Status:      execution.Status,
		Error:       err.Error(),
		StartTime:   execution.StartTime,
		EndTime:     execution.EndTime,
		Timestamp:   time.Now(),
	}

	// 发送到所有配置的通知地址
	for _, config := range configs {
		go n.sendNotification(config, message)
	}
}

// sendNotification 发送通知到指定URL
func (n *Notifier) sendNotification(config *models.NotificationConfig, message NotificationMessage) {
	// 创建请求头
	headers := map[string]string{
		"Content-Type": "application/json",
		"User-Agent":   "Alfred-CICD",
	}

	// 使用teemo发送POST请求
	var result interface{}
	result, err := teemo.SendHttpPostRequest[interface{}](context.TODO(), config.URL, headers, message)

	if err != nil {
		log.Printf("Failed to send notification to %s: %v", config.Name, err)
		return
	}

	log.Printf("Notification sent successfully to %s", config.Name)
	_ = result // 忽略响应结果
}

// SendSuccessNotification 发送成功通知（可选）
func (n *Notifier) SendSuccessNotification(flow *models.Flow, execution *models.FlowExecution) {
	// 获取通知配置
	configs, dbErr := n.db.GetNotificationConfigs()
	if dbErr != nil {
		log.Printf("Failed to get notification configs: %v", dbErr)
		return
	}

	if len(configs) == 0 {
		return
	}

	// 构建通知消息
	message := NotificationMessage{
		Type:        "flow_success",
		FlowName:    flow.Name,
		FlowID:      flow.ID,
		ExecutionID: execution.ID,
		Branch:      execution.Branch,
		CommitID:    execution.CommitID,
		Status:      execution.Status,
		StartTime:   execution.StartTime,
		EndTime:     execution.EndTime,
		Timestamp:   time.Now(),
	}

	// 发送到所有配置的通知地址
	for _, config := range configs {
		go n.sendNotification(config, message)
	}
}
